<template>
    <div class="change-car-appoint" @click="place.isShowLicense = false">
        <div class="place-fixed" v-show="place.isShow" @click.self="place.isShow = false">
            <div class="place-box">
                <div class="place-text">请选择车牌归属地</div>
                <div class="place-content">
                    <span :class="['place-item', place.index == index ? 'place-item-active' : '']"
                        v-for="(item, index) in place.list" :key="index" @click="changeActiveIdx(index)">{{ item }}</span>
                </div>
            </div>
        </div>
        <van-form @submit="onSubmit">
            <van-cell-group class="appoint-section font-size-26" inset>
                <van-field v-model="appointForm.data.spckmc" is-link name="spckmc" label="仓库" placeholder="请选择" required
                    readonly @click="openWarehousePicker" :rules="[{ required: true, message: '请选择仓库' }]" />
                <van-field v-model="appointForm.data.changeDate" is-link name="datetimePicker" label="过车日期"
                    placeholder="请选择" required readonly @click="openDatePicker"
                    :rules="[{ required: true, message: '请选择进仓日期' }]" />
                <div class="car-box">
                    <div class="car-text" @click="place.isShow = true">
                        <span>{{ place.text }}</span>
                    </div>
                    <van-field v-model="appointForm.data.cardNo" placeholder="填写车牌号" label="车牌号" @input="inputCar"
                         required :rules="[{ required: true, message: '请填写车牌号' }, {
                            pattern: /^[\a-\z\A-\Z0-9\u4e00-\u9fe5\uff1b\;]+$/,
                            message: '多个车牌请用分号；隔开',
                            trigger: 'onBlur'
                        }]" />
                    <div v-show="place.isShowLicense" class="car-list">
                        <div class="car-item" v-for="(item, index) in place.carList" :key="index"
                            @click="selectLicense(item)">
                            <span class="license">{{ item.dzzy6 }}</span>
                            <span>{{ item.dzzy7 }}</span>
                        </div>
                    </div>
                </div>
                <van-field v-model="appointForm.data.driverName" 
                @input="appointForm.data.driverName = appointForm.data.driverName.replace(' ', '')"
                @blur="appointForm.data.driverName = appointForm.data.driverName.replace(' ', '')"
                 placeholder="填写司机姓名" label="司机姓名" required
                    :rules="[{ required: true, message: '请填写司机姓名' }]" />
                <van-field v-model="appointForm.data.phone" placeholder="填写联系电话" label="联系电话" type="tel" />
                <van-field v-model="appointForm.data.idNo" placeholder="填写身份证号" label="身份证号" />
                <van-field v-model="appointForm.data.remark" placeholder="填写进仓备注" label="备注" />
            </van-cell-group>
            <div class="change-car-appoint-top display-flex justify-between align-center">
                <div class="title">
                    <span>过车货物信息：</span>
                </div>
                <van-button color="#CE0C0C" class="btn" @click="handleAdd"
                    v-hasPermi="['zhcloud:changeCar:add']">添加货物</van-button>
            </div>
            <div class="change-car-appoint-list">
                <div class="section font-size-26" v-for="(item, index) in appointForm.data.dtOpList" :key="index">
                    <div class="title display-flex justify-between align-center">
                        <span>{{ item.spzs }}</span>
                        <div class="display-flex align-center" @click="handleDelete(index)">
                            <van-image :src="deleteIcon" class="delete-icon" />
                            <span class="font-999999 ml-7">删除</span>
                        </div>
                    </div>
                    <div class="content">
                        <div class="item display-flex justify-between">
                            <div class="flex-item">
                                <span class="font-999999">纱支：</span>
                                <span>{{ item.wpggA }}</span>
                            </div>
                            <div class="flex-item">
                                <span class="font-999999">品牌：</span>
                                <span>{{ item.spcd }}</span>
                            </div>
                        </div>
                        <div class="item display-flex justify-between">
                            <div class="flex-item">
                                <span class="font-999999">条码：</span>
                                <span>{{ item.sptm }}</span>
                            </div>
                            <div class="flex-item">
                                <span class="font-999999">批号：</span>
                                <span>{{ item.spbh }}</span>
                            </div>
                        </div>
                        <div class="item display-flex justify-between">
                            <div class="flex-item">
                                <span class="font-999999">柜号：</span>
                                <span>{{ item.spgh }}</span>
                            </div>
                            <div class="flex-item">
                                <span class="font-999999">进仓日期：</span>
                                <span>{{ item.ssrqid }}</span>
                            </div>
                        </div>
                        <div class="item display-flex justify-between">
                            <div class="flex-item">
                                <span class="font-999999">库存重量：</span>
                                <span>{{ item.remainWeight }}吨</span>
                            </div>
                            <div class="flex-item">
                                <span class="font-999999">库存件数：</span>
                                <span>{{ item.remain }}件</span>
                            </div>
                        </div>
                        <div class="item display-flex justify-between">
                            <div class="flex-item">
                                <span class="font-999999">入仓车牌：</span>
                                <span>{{ item.dzzy6 }}</span>
                            </div>
                        </div>
                    </div>
                    <div class="footer">
                        <div class="item display-flex justify-between align-center">
                            <div>
                                <span class="font-999999">过车重量：</span>
                                <span>{{ item.spsl }}吨</span>
                            </div>
                            <div class="display-flex align-center">
                                <span class="font-999999">过车件数：</span>
                                <van-stepper v-model="item.spjs" step="0.001" :decimal-length="3" min="0.001"
                                    :max="item.remain" @change="changeSpjs(index)" />
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="change-car-appoint-btn display-flex align-center justify-between">
                <div class="left font-size-26">
                    <div class="display-flex">
                        <div>
                            <span>本次过车：</span>
                            <span class="font-CE0C0C">{{ appointForm.spjsSum }}</span>
                            <span> 件,</span>
                        </div>
                        <div>
                            <span>共</span>
                            <span class="font-CE0C0C">{{ appointForm.spslSum }}</span>
                            <span> 吨</span>
                        </div>
                    </div>
                </div>

                <van-button color="#255FB6" block class="btn" native-type="submit"
                    v-hasPermi="['zhcloud:changeCar:add']">提交过车</van-button>
            </div>
        </van-form>
        <van-action-sheet v-model:show="warehouseData.showPicker" title="请选择仓库" class="pb-30">
            <div class="select-warehouse display-flex flex-wrap">
                <div v-for="(item, index) in warehouseData.columns" :key="item.spckid"
                    :class="item.active ? 'active item' : 'item'" @click="warehouseConfirm(index)">
                    <span>{{ item.spckmc }}</span>
                </div>
            </div>
        </van-action-sheet>
        <van-calendar v-model:show="warehouseOutDateShow" color="#255FB6" :min-date="new Date(2018, 0, 1)"
            @confirm="warehouseOutDateConfirm" />
    </div>
</template>
<script setup lang="ts">
import { onMounted, reactive, ref, unref, getCurrentInstance,nextTick } from 'vue'
import type { Ref } from 'vue'
import { getCWarehouse23, storageCategoryCarInfoList } from '@/api/warehouse'
import { setChangeCarAdd } from '@/api/changeCar'
import { setReleaseAdd } from '@/api/pledge'
import { formatDate, getDaysBetween } from '@/utils/util'
import { useRoute, useRouter } from 'vue-router'
import { msgError, msgSuccess, msgConfirm } from '@/utils/message'
import { setLocalStorage, getLocalStorage } from '@/utils/localStorage'
import guaranteeIcon from '@/assets/images/guarantee.png'
import deleteIcon from '@/assets/images/delete.png'
import { WEIGHT_DIGIT, NUMBER_DIGIT, AMOUNT_DIGIT } from '@/utils/constant'
import { Dialog } from 'vant'

const route = useRoute()
const router = useRouter()
const userInfo: any = getLocalStorage('userInfo')
const warehouseData: any = reactive({
    showPicker: false,
    loading: false,
    list: [],
    columns: [],
    total: 0,
})
const customerData: any = reactive({
    query: {
        khid: userInfo.shopId,
    },
    detailRefresh: {
        warningWeight: 0,
        lockingWeight: 0,
        spsl: 0
    }
})
const warehouseOutDateShow: Ref<boolean> = ref(false)
const appointForm: any = reactive({
    data: {
        allname: userInfo.shopName,
        changeDate: formatDate(new Date()),
        remark: "",
        idNo: "",
        cardNo: "",
        driverName: "",
        phone: "",
        shopId: userInfo.shopId,
        dtOpList: []
    },
    spjsSum: 0,
    spslSum: 0,
})
let place: any = reactive({
    list: ['粤', '浙', '冀', '闽', '京', '津', '沪',
        '渝', '豫', '云', '辽', '黑', '湘', '皖',
        '鲁', '新', '苏', '赣', '鄂', '桂', '甘',
        '晋', '蒙', '陕', '吉', '贵', '贵', '藏',
        '川', '宁', '琼'
    ],
    text: '粤',
    index: 0,
    isShow: false,
    isShowLicense: false,
    carAllList: [],
    carList: []
})
onMounted(() => {
    getStorage()
    warehouse()
    getCarList()
})
function inputCar(e: any) {
    let value = e.target.value;
    value = value.replaceAll(' ', '');
    value = value.replace(/[\u4e00-\u9fa5]/ig, '');
    nextTick(() => {
        appointForm.data.cardNo = value;
    })
    if (value) {
        place.carList = place.carAllList.filter((item: any) => {
            return item.dzzy6.indexOf(value) >= 0;
        })
        if (place.carList.length) {
            place.isShowLicense = true;
        } else {
            place.isShowLicense = false;
        }
    } else {
        place.carList = [];
        place.isShowLicense = false;
    }
}
function selectLicense(item: any) {
    place.isShowLicense = false;
    let license = item.dzzy6;
    if (checkChinese(license)) {
        place.text = license.slice(0, 1);
        license = license.slice(1);
        place.list.map((text: string, index: number) => {
            if (text == place.text) {
                place.index = index;
                return;
            }
        })
    }
    nextTick(() => {
        appointForm.data.cardNo = license;
        appointForm.data.driverName = item.dzzy7;
        appointForm.data.phone = item.dzzy8;
        appointForm.data.idNo = item.dzzy10;
    })
}

function changeActiveIdx(index: number) {
    place.index = index;
    place.text = place.list[index]
    place.isShow = false;
}
function getCarList() {
    storageCategoryCarInfoList({ shopid: userInfo.shopId }).then((res: any) => {
        place.carAllList = res.data || [];
        place.carList = res.data || [];
        place.text = getLocalStorage('changeCarCarText') || '粤';
    })
}

function checkChinese(str: string) {
    var reg = new RegExp("[\\u4E00-\\u9FFF]+", "g");
    return reg.test(str);
}
function getStorage() {
    const data = getLocalStorage('changeCar')
    if (data) {
        const dtOpList = data.dtOpList
        const changeDate = data.changeDate
        for (let i in dtOpList) {
            dtOpList[i].spjs = parseFloat(dtOpList[i].spjs) ? parseFloat(dtOpList[i].spjs) : parseFloat(dtOpList[i].spjs2)
            dtOpList[i].spsl = (parseFloat(dtOpList[i].spjs) * parseFloat(dtOpList[i].spjsl) * 0.001).toFixed(WEIGHT_DIGIT)
            if (getDaysBetween(dtOpList[i].ssrqid, changeDate) === -1) {
                return msgError('过车日期需要大于入仓日期，请重新选择！')
            }
        }
        setLocalStorage('changeCar', data)
        appointForm.data = reactive(data)
        getSum()
    }
}

function warehouse() {
    warehouseData.loading = true
    getCWarehouse23({}).then((res: any) => {
        warehouseData.loading = false
        const data = res.data
        warehouseData.list = data
        warehouseData.columns = data.map((a: any) => {
            return {
                spckid: a.spckid, spckmc: a.spckmc, active: false
            }
        })
    })
}

function warehouseOutSubmit() {
    const inp = appointForm.data.dtOpList
    const dtOpList = []
    for (let i in inp) {
        dtOpList.push({
            spdzld: inp[i].spdzld,
            spjs: Number(inp[i].spjs)
        })
    }
    let form = JSON.parse(JSON.stringify(appointForm.data))
    form.cardNo = place.text + form.cardNo
    const params = {
        ...form,
        dtOpList: dtOpList
    }
    setChangeCarAdd(params).then(() => {
        msgSuccess('提交成功')
        router.push({ path: '/changeCar' })
    })
}

async function onSubmit() {
    const dtOpList: any = appointForm.data.dtOpList
    if (dtOpList && dtOpList.length == 0) return msgError('请添加货物')

    msgConfirm('是否确认过车？').then((res: any) => {
        warehouseOutSubmit()
    })
}

function openWarehousePicker() {
    warehouseData.showPicker = !warehouseData.showPicker
}

function warehouseConfirm(index: number) {
    let data = getLocalStorage('changeCar')
    appointForm.data.spckmc = warehouseData.list[index].spckmc
    appointForm.data.spckid = warehouseData.list[index].spckid
    if (data) {
        data.spckmc = warehouseData.list[index].spckmc
        data.spckid = warehouseData.list[index].spckid
    }
    if (data && data.dtOpList.length > 0) {
        data.dtOpList = []
        setLocalStorage('changeCar', data)
        appointForm.data = data
        getSum()
    }
    openWarehousePicker()
}

function openDatePicker() {
    warehouseOutDateShow.value = !warehouseOutDateShow.value
}

function warehouseOutDateConfirm(value: string) {
    appointForm.data.changeDate = formatDate(value)
    openDatePicker()
}

function handleDelete(index: number) {
    msgConfirm('是否确认删除货物？').then((res: any) => {
        let data = getLocalStorage('changeCar')
        data.dtOpList.splice(index, 1)
        setLocalStorage('changeCar', data)
        appointForm.data = data
        getSum()
    })

}

function handleAdd() {
    if (!appointForm.data.spckmc) return msgError('请先选择货物仓库！')
    setLocalStorage('changeCar', appointForm.data)
    setLocalStorage('changeCarCarText', place.text)
    router.push({ path: '/changeCar/add', query: { spckmc: appointForm.data.spckmc, dtOpList: JSON.stringify(appointForm.data.dtOpList) } })
}

function changeSpjs(index: number) {
    const dtOpList = appointForm.data.dtOpList
    const spsl = parseFloat(dtOpList[index].spjs) * parseFloat(dtOpList[index].spjsl) * 0.001
    dtOpList[index].spsl = spsl.toFixed(WEIGHT_DIGIT)
    setLocalStorage('changeCar', appointForm.data)
    getSum()
}

function getSum() {
    let spjsSum: number = 0
    let spslSum: number = 0
    const data: any = appointForm.data.dtOpList
    for (let i in data) {
        data[i].spje = data[i].spje ? data[i].spje : 0
        spjsSum += parseFloat(data[i].spjs)
        spslSum += parseFloat(data[i].spsl)
    }
    appointForm.spjsSum = parseFloat(spjsSum.toFixed(NUMBER_DIGIT))
    appointForm.spslSum = parseFloat(spslSum.toFixed(WEIGHT_DIGIT))
}
</script>
<style lang="scss" scoped>
.change-car-appoint {
    padding-bottom: 150px;

    .appoint-section {
        margin-top: 36px;
        border-radius: 10px;
    }

    .guarantee {
        .msg {
            width: 674px;
            height: 170px;
            background: #F3F4F7;
            border-radius: 8px;
            margin: 51px auto;
            padding-top: 44px;

            .label {
                display: inline-block;
                width: 250px;
                text-align: left;
                margin-left: 130px;
            }
        }

        .btn {
            width: 674px;
            margin: 60px auto 80px;
        }
    }

    &-top {
        padding: 36px;
        font-size: 26px;

        .title {
            border-left: 8px solid #CE0C0C;
            padding-left: 26px;
        }

        .guarantee-btn {
            height: 60px;
            border-radius: 8px;
            color: #CE0C0C !important;
        }

        .btn {
            height: 60px;
            border-radius: 8px;
        }
    }

    &-list {
        padding: 0 36px;

        .section {
            border-radius: 10px;
            background-color: #fff;
            padding: 26px;
            margin-bottom: 20px;

            .title {
                padding-left: 18px;
                margin-bottom: 26px;

                .delete-icon {
                    width: 25px;
                    height: 28px;
                }
            }

            .content {
                border-top: 1px solid #EEEEEE;
                padding: 26px 0;

                .item {
                    padding-bottom: 10px;
                }

            }

            .footer {
                border-top: 1px solid #EEEEEE;
                padding: 43px 0 0;

                .item {
                    padding-bottom: 10px;
                }
            }
        }
    }

    &-btn {
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        width: 100%;
        height: 140px;
        background-color: #fff;

        .left {
            margin-left: 35px;
        }

        .btn {
            border-radius: 10px;
            width: 199px;
            height: 90px;
            margin-right: 36px;
        }
    }

    .select-warehouse {
        padding: 15px 20px 30px;
        max-height: 550px;
        font-size: 26px;

        .item {
            min-width: 150px;
            padding: 0 20px;
            display: inline-block;
            height: 60px;
            line-height: 60px;
            color: #999;
            text-align: center;
            border-radius: 30px;
            border: 1px solid #999;
            margin: 15px;

            &.active {
                color: #fff;
                border: 1px solid #255FB6;
                background: #255FB6;
            }
        }
    }
    .place-fixed {
        position: fixed;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        background: rgba(0, 0, 0, 0.4);
        z-index: 9999;

        .place-box {
            box-sizing: border-box;
            padding: 30px;
            position: absolute;
            left: 0;
            right: 0;
            bottom: 0;
            width: 100%;
            height: 620px;
            font-size: 32px;
            background: #FFFFFF;
            border-radius: 16px 16px 0px 0px;

            .place-text {
                margin-bottom: 30px;
                font-family: PingFangSC-Semibold, PingFang SC;
                font-weight: 600;
                color: #333333;
            }

            .place-content {
                display: flex;
                flex-wrap: wrap;

                .place-item {
                    margin-right: 20px;
                    margin-bottom: 22px;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    width: 80px;
                    height: 80px;
                    background: #F5F5F5;
                    border-radius: 8px;

                    &:nth-child(7n) {
                        margin-right: 0px !important;
                    }
                }

                .place-item-active {
                    background: #108EE9;
                    color: #FFFFFF;
                }

            }

        }
    }

    .car-box {
        position: relative;

        .car-text {
            box-sizing: border-box;
            position: absolute;
            z-index: 2;
            left: 150px;
            top: 10px;
            display: flex;
            align-items: center;
            width: 66px;
            height: 60px;
            background: #E3EFFC;
            border-radius: 4px;
            border: 2px solid #D6E9FC;
            font-size: 30px;
            font-weight: 400;
            color: #333333;

            span {
                margin-left: 5px;
            }

            &::after {
                position: absolute;
                right: 5px;
                top: 50%;
                transform: translateY(-50%);
                content: '';
                width: 0;
                height: 0;
                border-top: 10px solid #333;
                border-right: 10px solid transparent;
                border-left: 10px solid transparent;
            }
        }

        .car-list {
            padding: 0 30px;
            position: absolute;
            left: 0;
            right: 0;
            z-index: 99;
            top: 90px;
            max-height: 352px;
            background: #FFFFFF;
            box-shadow: 2px 8px 8px 8px rgb(29 35 41 / 5%) !important;
            font-size: 30px;
            overflow-y: auto;

            &::-webkit-scrollbar {
                display: none;
            }

            .car-item {
                z-index: 100;
                box-sizing: border-box;
                width: 100%;
                height: 88px;
                line-height: 88px;
                border-bottom: 1px solid #F6F6F6;

                .license {
                    display: inline-block;
                    margin-right: 50px;
                }
            }
        }
    }
}
</style>